package autoTest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import autoTest.command.RequestCmd;
import autoTest.utils.TextUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class ResponseMaker {
	
	public static String makeResponse(int cmd, String content) {
		String ret = new String();
		if (cmd == RequestCmd.GET) {
			if (TextUtils.isEmpty(content)) {
				return null;
			}
			
			JSONArray jaSend = new JSONArray();
			try {
				if (readAllFile(content, jaSend) == 0) {
					ret = jaSend.toString();
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
		} else {
			return null;
		}
		return ret;
	}
	
	private static int readAllFile(String filePath, JSONArray ja) throws IOException, JSONException{
		File file = new File(filePath);
		System.out.println("--------------> 9");
		if (!file.exists()) {
			return -1;
		}
		
		System.out.println("--------------> 10");
		if (file.isDirectory()) {
			readFolder(file, ja);
		} else if(file.isFile() && file.exists()){ //判断文件是否存在
			System.out.println("--------------> 11");
			readFile(file, ja);
			System.out.println("--------------> 12");
	    } else {
	        return -1;
	    }
		return 0;
	}
	
	private static void readFolder(File file, JSONArray ja) throws IOException, JSONException {
		File[] files = file.listFiles();
		for(File ele : files) {
			if (ele.isDirectory()) {
				readFolder(ele, ja);
			} else {
				readFile(ele, ja);
			}
		}
	}
	
	private static void readFile(File file, JSONArray ja) throws IOException, JSONException {
		InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");//考虑到编码格式
		BufferedReader bufferedReader = new BufferedReader(read);
		String lineTxt = new String("");
		String fileContent = new String("");
		while((lineTxt = bufferedReader.readLine()) != null){
			fileContent = fileContent + lineTxt;
		}
		read.close();
		JSONObject jo = JSONObject.fromObject(fileContent);
		ja.add(jo);
	}
}
